package codingforgreat.class35;

public class Lc687 {
    public class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode() {}
     TreeNode(int val) { this.val = val; }
     TreeNode(int val, TreeNode left, TreeNode right) {
         this.val = val;
         this.left = left;
         this.right = right;
     }
 }
    public class Info{
        int lenx;
        int len;
        public Info(int x,int y){
            lenx = x;
            len = y;
        }
    }
    public int longestUnivaluePath(TreeNode root) {
        if(root == null){
            return 0;
        }
        return Math.max(process(root).lenx,process(root).len) - 1;
    }
    public Info process(TreeNode node){
        if(node == null){
            return new Info(0,0);
        }
        Info l = process(node.left);
        Info r = process(node.right);
        int len = 0;
        int lenx = 1;
        if (node.left != null && node.left.val == node.val) {
            lenx = l.lenx + 1;
        }
        if (node.right != null && node.right.val == node.val) {
            lenx = Math.max(lenx,r.lenx + 1);
        }
        // 不要求从x出发，最大路径
        len = Math.max(Math.max(l.len, r.len), lenx);
        if (node.left != null && node.right != null && node.left.val == node.val && node.right.val == node.val) {
            len = Math.max(len, l.lenx + r.lenx + 1);
        }
        return new Info(lenx, len);
    }
}
